//
//  BannerView.m
//  bannerViewTest
//
//  Created by 谢特 on 2017/5/16.
//  Copyright © 2017年 xiete. All rights reserved.
//

#import "XTBannerView.h"
#import "XTBannerCell.h"
@interface XTBannerView ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, weak) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSMutableArray *allImags;  //所有图片下标集合
@property (nonatomic, assign) NSInteger currentPage;

@property (nonatomic, strong) NSTimer *timer;
@end
@implementation XTBannerView

+ (instancetype)initBannaerViewWithImags:(NSArray *)imageNames WithFrame:(CGRect)frame{
    XTBannerView *bannerView = [[XTBannerView alloc] initWithFrame:frame];
    bannerView.images = imageNames;
    return bannerView;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]){
        [self addSubview: self.collectionView];
        [self addSubview:self.pageControl];
        [self initAttribute];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.flowLayout.itemSize = self.frame.size;
    self.collectionView.frame = self.bounds;
    self.pageControl.frame = CGRectMake(0, self.bounds.size.height - 30, self.bounds.size.width, 30);
//    NSLog(@"%f",self.frame.origin.y);
    //用于下拉放大效果时禁止滚动
    if (self.bounds.size.width > [UIApplication sharedApplication].keyWindow.bounds.size.width){
        [self.timer invalidate];
        self.collectionView.scrollEnabled = NO;
    }else{
        [self startTimer];
        self.collectionView.scrollEnabled = YES;
    }
    
    self.pageControl.currentPage = self.currentPage;
    if (self.images.count > 1){
        [self.collectionView reloadData];
        if (self.needCycle){
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:100*_images.count+self.currentPage inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        }else{
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentPage inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        }
        
    }
    
}

- (void)initAttribute{
    self.needCycle = NO;
    self.bounces = NO;
    self.scrollTime = 0.f;
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.allImags.count;
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XTBannerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([XTBannerCell class]) forIndexPath:indexPath];
    NSInteger index = [self.allImags[indexPath.row] integerValue];
    if (self.placeholderImage.length > 0){
        cell.placeholder = self.placeholderImage;
    }
    cell.imageData = self.images[index];
    return cell;
}

#pragma mark -- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.delegate respondsToSelector:@selector(bannerView:didSelectItemAtIndexPath:)]){
        [self.delegate bannerView:self didSelectItemAtIndexPath:indexPath.row % self.images.count];
    }
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    
}


#pragma mark -- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{

    CGFloat offSetX = targetContentOffset->x;
    NSInteger integer = [[NSString stringWithFormat:@"%.f",(offSetX/scrollView.bounds.size.width)] integerValue];
    NSInteger index = integer % self.images.count;
    self.currentPage = index;
    self.pageControl.currentPage = index;
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (_images.count < 2){
        return;
    }
    NSInteger integer = [[NSString stringWithFormat:@"%.f",(scrollView.contentOffset.x/scrollView.bounds.size.width)] integerValue];
    NSInteger index = integer % self.images.count;
    if (self.needCycle){
         [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:100*self.images.count+index inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    }
//    self.currentPage = index;
//    self.pageControl.currentPage = index;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.timer invalidate];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self startTimer];
}

#pragma mark - publicMethod
- (void)scrollToPageOfIndex:(NSInteger)pageIndex Animation:(BOOL)animation{
    if (self.images.count < 2) return;
    if (pageIndex < self.images.count){
        NSInteger indexRow = pageIndex;
        if (self.needCycle){
            indexRow = 100 * self.images.count + pageIndex;
        }
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexRow inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:animation];
        self.currentPage = pageIndex;
    }
}

#pragma mark- privateMethod
- (void)startTimer{
    if (self.scrollTime <= 0.8) return;
    if (self.timer){
        [self.timer invalidate];
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:_scrollTime target:self selector:@selector(scrollCell) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)scrollCell{
    //保证图片数量大于1，并且开启了循环滚动
    if (self.allImags.count > 1){
        //获取collectionview当前显示的cell的indexPath
        NSArray *indexPaths =  [self.collectionView indexPathsForVisibleItems];
        if (indexPaths.count < 1) return;
        NSIndexPath *indexPath = indexPaths.firstObject;
        
        NSInteger currentRow = indexPath.row;
        
        if (currentRow % self.images.count == 0){
            currentRow = 100 * self.images.count;
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:currentRow inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        }
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:currentRow + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
        self.currentPage = (indexPath.row +1) % self.images.count;
    }else{
        [self.timer invalidate];
    }
}


#pragma mark -getAndSet
- (void)setNeedCycle:(BOOL)needCycle{
    _needCycle = needCycle;
    if (self.scrollTime > 0.8) _needCycle = YES;   //设置了自动滚动时间需要开启循环滑动
    if(self.images.count > 0){  //需要重新设置数据源
        [self setImages:self.images];
    }
}

- (void)setImages:(NSArray *)images{
    _images = images;
    NSAssert(_images.count > 0, @"images can't be empty");
    self.pageControl.numberOfPages = images.count;
    self.pageControl.currentPage = 0;
    self.pageControl.hidden = NO;
     [self.allImags removeAllObjects];
    if (_images.count < 2){
        [self.allImags addObject:@(0)];
        self.pageControl.hidden = YES;
        return;
    }
    if (self.needCycle){
        for (int i = 0; i<200; i++){
            for (int j= 0 ;j<_images.count;j++){
                [self.allImags addObject:@(j)];
            }
        }
    }else{
        for (int j= 0 ;j<_images.count;j++){
            [self.allImags addObject:@(j)];
        }
    }
    
    [self.collectionView reloadData];
    if (self.needCycle){     //初始化，滑动到数组最中间的位置
         [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:100*_images.count inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    }
   
}

- (void)setScrollTime:(NSTimeInterval)scrollTime{
    _scrollTime = scrollTime;
     [self.timer invalidate];
    if (_scrollTime > 0.8){
        self.needCycle = YES;  // 设置了自动滚动默认开启循环滑动
        [self startTimer];
    }
}

- (void)setCurrentPage:(NSInteger)currentPage{
    _currentPage = currentPage;
    self.pageControl.currentPage = _currentPage;
}

- (UICollectionView *)collectionView{
    if (!_collectionView){
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = self.frame.size;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        _flowLayout = layout;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _collectionView.scrollsToTop = NO;
        _collectionView.bounces = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.alwaysBounceVertical = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[XTBannerCell class] forCellWithReuseIdentifier:NSStringFromClass([XTBannerCell class])];
        
    }
    return _collectionView;
}

- (void)setBounces:(BOOL)bounces{
    _bounces = bounces;
    self.collectionView.bounces = _bounces;
}

- (NSInteger)currentIndexPage{
    if (!self.images||self.images.count < 2) return 0;
    return self.currentPage;
}

- (UIPageControl *)pageControl{
    if (!_pageControl){
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 30, self.bounds.size.width, 30)];
        _pageControl.userInteractionEnabled = NO;
    }
    return _pageControl;
}

- (NSMutableArray *)allImags{
    if (!_allImags){
        _allImags = [[NSMutableArray alloc] init];
    }
    return _allImags;
}
@end
